package com.cykj.service.impl;

import com.cykj.dto.ResponseDTO;
import com.cykj.entity.MenuDO;
import com.cykj.mapper.MenuMapper;
import com.cykj.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Program: Mooc-Admin
 * @Package: com.cykj.service.impl
 * @Author: 张俊杰
 * @Create: 2025-07-09 12:30
 * @Description: TODO
 * @Vision: 1.0
 **/
@Service
public class MenuServiceImpl implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public ResponseDTO getListMenu(Integer roleId) {
        List<MenuDO> listMenu = menuMapper.getListMenu(roleId);
        List<MenuDO> list = treeTransfer(listMenu);
        return ResponseDTO.success(list);
    }

    @Override
    public ResponseDTO getListMenuAssignNot(Integer roleId) {
        List<MenuDO> menuDOS = menuMapper.getListMenuAssignNot(roleId);
        List<MenuDO> list = treeTransfer(menuDOS);
        return ResponseDTO.success(list);
    }

    @Override
    public ResponseDTO removePermission(Integer roleId, List<Integer> menuIds) {
        Integer i = menuMapper.removePermission(roleId, menuIds);
        if (i > 0) {
            return ResponseDTO.effectRow(i);
        }
        return ResponseDTO.error("权限删除失败");
    }

    @Override
    public ResponseDTO addPermission(Integer roleId, List<Integer> menuIds) {
        Integer i = menuMapper.addPermission(roleId, menuIds);
        if (i > 0) {
            return ResponseDTO.effectRow(i);
        }
        return ResponseDTO.error("权限添加失败");
    }

    /**
     * @Description:用hashmap快速查找
     * @Param:[list]
     * @Return:java.util.List<com.cykj.entity.CyMenuDO>
     */
    private List<MenuDO> treeTransfer(List<MenuDO> list) {
        // 用 map 快速找到每个节点
        Map<Integer, MenuDO> menuMap = new HashMap<>();
        for (MenuDO menu : list) {
            menuMap.put(menu.getMenuId(), menu);
        }
        // 保存根节点（parentId = 0）
        List<MenuDO> roots = new ArrayList<>();
        for (MenuDO menu : list) {
            if (menu.getMenuParentId() == 0) {
                roots.add(menu);
            } else {
                MenuDO parent = menuMap.get(menu.getMenuParentId());
                if (parent != null) {
                    // 拼接路径（注意处理斜杠）
                    String parentPath = parent.getMenuPath();
                    String childPath = menu.getMenuPath();
                    menu.setMenuPath(parentPath + childPath);
                    parent.getChildren().add(menu);
                }
            }
        }
        return roots;
    }
}
